<template>
  <v-list nav>
    <template v-for="(item, index) in categoryTree">
      <v-list-item
        v-if="!item.children || !item.children.length"
        :key="index"
        :to="{name: 'InvestCategory', params: {id: item.id}}"
        link
      >
        <v-list-item-title>{{item.name}}</v-list-item-title>
      </v-list-item>
      <v-list-group v-else :key="index" :value="item.active" no-action>
        <template v-slot:activator>
          <v-list-item-title>{{item.name}}</v-list-item-title>
        </template>
        <v-list-item
          v-for="(subItem, subIndex) in item.children"
          :key="subIndex" link :to="{name: 'InvestCategory', params: {id: subItem.id}}"
        >
          <v-list-item-title v-text="subItem.name"></v-list-item-title>
        </v-list-item>
      </v-list-group>
    </template>
  </v-list>
</template>

<script lang="ts">
import { Component, Vue} from 'vue-property-decorator';

@Component
export default class InvestNav extends Vue {
  protected categoryTree: TypeFrontCategory.CategoryTreeItem[] = [];
  protected async getCategoryTree(): Promise<void> {
    const { data } = await this.$api.front.categoryTree<TypeFrontCategory.CategoryTreeItem[]>({section_id: 2});
    if ('InvestCategory' === this.$route.name) {
      const activeId = Number(this.$route.params.id);
      for (const cat1 of data) {
        if (cat1.id === activeId) {
          cat1.active = true;
        } else if (cat1.children && cat1.children.length) {
          for (const cat2 of cat1.children) {
            if (cat2.id === activeId) {
              cat2.active = true;
              cat1.active = true;
              continue;
            }
          }
        }
      }
    }
    this.categoryTree = data;
  }
  protected created(): void {
    this.getCategoryTree();
  }
}
</script>

<style lang="scss" scoped>
  .v-list .v-list-item--active {
    color: $primary;
  }
</style>
